package com.yqr.common.enums;

import java.util.HashMap;
import java.util.Map;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

public class BaseEnumFactory implements ConverterFactory<String, IBaseEnum> {
    /**
     * 缓存IBaseEnum实现类
     */
    private static final Map<Class<?>, Converter<String,? extends IBaseEnum>> cacheMap = new HashMap<>();

    @Override
    public <T extends IBaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        Converter<String, ? extends IBaseEnum> converter = cacheMap.get(targetType);
        if (converter == null) {
            converter = new BaseEnumImpl<T>(targetType);
            cacheMap.put(targetType, converter);
        }
        return (Converter<String, T>) converter;
    }

    /**
     * 内部转换类
     * @author zhaoyong
     *
     * @param <T>
     */
    private class BaseEnumImpl<T extends IBaseEnum> implements Converter<String, T> {

        private Class<T> clazz;

        private Map<String, T> enumMap = new HashMap<>();

        private BaseEnumImpl(Class<T> clazz) {
            this.clazz = clazz;
            T[] enums = clazz.getEnumConstants();
            for (T t : enums) {
                enumMap.put(t.getClass().getSimpleName(), t);
            }
        }

        @Override
        public T convert(String source) {
            return enumMap.get(source);
        }
    }
}
